<template>
  <div>
    <input type="text" v-model="kw" />
    <ul>
      <li v-for="item in listData">
        {{ item.title }}
      </li>
    </ul>
    <button @click="click">click</button>
    <button @click="disconnect">disconnect</button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { onMounted,onUnmounted} from "vue";
// Create WebSocket connection.
const kw = ref("");
const listData = ref([]);
const lockReconnect = ref(false)
const socket = ref(null)
// Connection opened



const initWebSocket = () => {
  socket.value = new WebSocket("ws://127.0.0.1:3000");
  socket.value.onopen = websocketOnopen;
  socket.value.onmessage = websocketOnmessage;
  socket.value.onerror = websocketOnerror;
  socket.value.onclose = websocketOnclose;
}


const websocketOnopen = () => {
  console.log("WebSocket连接成功");
  socket.value.send(
    JSON.stringify({ value: "摄像头" })
  );
  lockReconnect.value = true
};
// Listen for messages
const  websocketOnmessage = (event) => {
  // console.log(event.data);
  let data = JSON.parse(event.data)
  if (data.type == 1) return
  console.log(data);
  let obj = { 
    title: event.data,
  };
  listData.value.push(obj);
};

const websocketOnerror = (e) => {
  console.log("WebSocket连接发生错误");
  reconnect()
};

const websocketOnclose = (e) => {
  console.log("connection closed (" + e.code + ")");
  reconnect();
};

const websocketSend = (text) => { // 数据发送
  try {
    socket.value.send(text);
  } catch (err) {
    console.log("send failed (" + err.code + ")");
  }
}

const click = () => {
  websocketSend(kw.value)
};


const disconnect = () => {
  socket.value.close();
};


const reconnect = () => {
  if (lockReconnect.value) return
  lockReconnect.value = true
  //没连接上会一直重连，设置延迟避免请求过多
  setTimeout(function () {
    console.info("尝试重连...");
    initWebSocket()
    lockReconnect.value = false;
  }, 5000);
}

onMounted (() => {
  initWebSocket()
})

onUnmounted(() => {
  socket.value.close()
})

</script>

<style lang="scss" scoped></style>